
 #  Basic example blacklist class. This class takes a text file with regex
 #  rules against which URL's are tested.
 #  The default file location is (base_path)/blacklist.txt
 # 
 
from src.gadgets import GadgetBlacklist;
from lib import Config;

class BasicGadgetBlacklist(GadgetBlacklist):
	

	def __init__(self, filename = False):
		self.__rules_ = [];

		if (filename == False):
			filename = Config.get('base_path') + '/blacklist.txt';
		
		import os;

		if (os.path.exists(filename)):
			try:
				fp = open(filename, 'r');
				self.__rules_ = fp.read().split("\n");
				fp.close();
			
			except:
				raise Exception, 'File read error';
		
	 # 
	 #  Check the URL against the blacklist rules
	 # 
	 #  @param string url
	 #  @return boolean is blacklisted or not?
	 #
	
	def isBlacklisted(self, url):
		for rule in self.__rules_:
			if (preg_match(rule, url)):
				return True;
			
		return False;


# Basic implementation of a gadget spec factory.

# 
from src.gadgets import GadgetSpecFactory;
class BasicGadgetSpecFactory(GadgetSpecFactory):
	
	def __init__(self, request, response, fetcher):
		self.request = request;
		self.response = response;
		self.__fetcher_ = fetcher;
	
	def getGadgetSpec(self, context):
		return self.getGadgetSpecUri(context.getUrl(), context.getIgnoreCache());

	# 
	# Retrieves a gadget specification from the cache or from the Internet.

	# 
	def getGadgetSpecUri(self, url, ignoreCache):
		if (ignoreCache):
			return self.__fetchFromWeb_(url, True);

		return self.__fetchFromWeb_(url, False);

	# 
	# Retrieves a gadget specification from the Internet, processes its views and

	# adds it to the cache.

	# 
	def __fetchFromWeb_(self, url, ignoreCache):
		remoteContentRequest = RemoteContentRequest(url);
		remoteContentRequest.getRequest(url, ignoreCache);
		spec = self.fetcher.fetchRequest(remoteContentRequest);
		specParser = GadgetSpecParser();
		context = ProxyGadgetContext(self.request, self.response, url);
		gadgetSpec = specParser.parse(spec.getResponseContent(), context);
		return gadgetSpec;
